<template>
  <transition name="slide-fade">
    <div style="height: 100%">
      <img src="../assets/imgs/indexBg1.jpg" alt="">
      <el-container>
        <el-header>房间号<span style="color: gold">{{room_id}}</span></el-header>
        <!--<div style="text-align: center">-->
          <!--手指滑动头像选择卧底-->
        <!--</div>-->
        <!--<div class="players">-->
          <!--<div class="hasplayer">-->
            <!--<div v-for="(player,index) in playInfo">-->
              <!--<div class="imgBox"-->
                   <!--:style="[transformIndex(index),transform(index)]"-->
                   <!--@touchmove.stop.capture.prevent="touchmove"-->
                   <!--@touchstart.stop.capture.prevent="touchstart"-->
                   <!--@touchend.stop.capture.prevent="touchend"-->
                   <!--@touchcancel.stop.capture.prevent="touchend"-->
                   <!--@mousedown.stop.capture.prevent="touchstart"-->
                   <!--@mouseup.stop.capture.prevent="touchend"-->
                   <!--@mousemove.stop.capture.prevent="touchmove"-->
                   <!--@mouseout.stop.capture.prevent="touchend"-->
                   <!--@webkit-transition-end="onTransitionEnd(index)"-->
                   <!--@transitionend="onTransitionEnd(index)"-->
              <!--&gt;-->
                  <!--<img :src="player.head_img" alt="">-->
                  <!--<div class="name" :style="{'opacity':index === temporaryData.currentPage?1:0}">-->
                    <!--{{player.nickname}}-->
                  <!--</div>-->

              <!--</div>-->
            <!--</div>-->


            <!--&lt;!&ndash;<div  v-if="index==0"  class="mark" style="background: #ff0;color: brown">房东</div>&ndash;&gt;-->
            <!--&lt;!&ndash;<div  v-if="index!=0"  class="mark">已准备</div>&ndash;&gt;-->
          <!--</div>-->

        <!--</div>-->
        <div class="Tstext">
          点击选中你心中的怀疑对象
        </div>
        <div class="players">
          <!--<div style="position: relative;">-->
          <!--<div class="houseOwner">-->
          <!--<img src="../assets/imgs/bg.png" alt="">-->
          <!--</div>-->
          <!--<div class="houseOwnerMark">-->
          <!--<img src="../assets/imgs/king.png" alt="">-->
          <!--</div>-->
          <!--</div>-->

          <div class="hasplayer" v-for="(player,index) in playInfo" @click="vote(player['player_id'])">
            <img :src="player.head_img" alt="">
            <div  v-if="player['player_id']==spy"  class="mark">卧底</div>
          </div>
        </div>
        <!--<div class="poll" @click="vote(playInfo[temporaryData.currentPage]['player_id'])" v-if="!isPoll">-->
          <!--他就是卧底-->
        <!--</div>-->
        <div class="result" v-if="isPoll">
          <div class="pollHeader">投票结果</div>
          <div class="pollContent">
            <div class="options" v-for="(option,index) in resultInfo['vote']">
              <div>
                {{option.nickname}}
              </div>
              <div>
                {{option.vote_count}}
              </div>
            </div>
          </div>

        </div>
      </el-container>
    </div>
  </transition>
</template>

<script>
  import detectPrefixes from '../api/detect-prefixes.js'
  export default {
    name: 'poll',
    data:()=>({
      isPoll:false,
      room_id:'',
      player_id:'',
      spy:-1,
      playInfo:[],
      loop:function () {

      },
      resultInfo:{},
      basicdata: {
        start: {},
        end: {}
      },
      temporaryData: {
        prefixes: detectPrefixes(),
        offsetY: '',
        poswidth: 0,
        posheight: 0,
        lastPosWidth: '',
        lastPosHeight: '',
        lastZindex: '',
        rotate: 0,
        lastRotate: 10,
        visible:3,
        tracking: false,
        animation: false,
        currentPage:  0,
        opacity: 1,
        lastOpacity: 0,
        swipe: false,
        zIndex: 10
      }
    }),
    computed: {
      // 划出面积比例
      offsetRatio () {
        let width = this.$el.offsetWidth
        let height = this.$el.offsetHeight
        let offsetWidth = width - Math.abs(this.temporaryData.poswidth)
        let offsetHeight = height - Math.abs(this.temporaryData.posheight)
        let ratio = 1 - (offsetWidth * offsetHeight) / (width * height) || 0
        return ratio > 1 ? 1 : ratio
      },
      // 划出宽度比例
      offsetWidthRatio () {
        let width = this.$el.offsetWidth
        let offsetWidth = width - Math.abs(this.temporaryData.poswidth)
        let ratio = 1 - offsetWidth / width || 0
        return ratio
      }
    },
    methods:{
      goBack(){

        // 禁止回退

        history.pushState(null, null, null,null,null);
        return false
      },
      getUserInfo(){
        this.$axios.post(this.urlList.authUrl + '/api/game/get_room_info',{
          room_id:this.room_id
        }).then((res)=>{
          let data = res.data.data.member
          for(let k in res.data.data.member){
            if(data[k].player_id != this.player_id && data[k].status!=2){
              this.playInfo.push(data[k])
            }
          }
        })
      },
      vote(aim_id){
        if(!this.isPoll){
          this.$axios.post(this.urlList.authUrl + '/api/game/do_vote',{
            room_id:this.room_id,
            player_id:this.player_id,
            aim_id:aim_id
          }).then((res)=>{
            if(res.data.error == 200){
              console.log(res)
              this.loop = setInterval(this.getResult,1000)
              this.isPoll = true
              this.spy = aim_id
            }else{
              this.$message(res.data.message)
              return false
            }

          })

        }else{
          alert('您已经投过票了')
        }
      },
      back(page){
        let that = this;
        setTimeout(function () {
          that.$router.replace({name:page})
        },1000)
      },
      getResult(){
        this.$axios.post(this.urlList.authUrl + '/api/game/get_vote_result',{
          room_id:this.room_id
        }).then((res)=>{
          if(res.data.error == 200){
            this.resultInfo = res.data.data

            if(res.data.message == '平民胜利'){
              alert('平民胜利')
              window.localStorage.removeItem('num')
              this.back('result')
            }else if(res.data.message == '卧底胜利'){
              alert('卧底胜利')
              window.localStorage.removeItem('num')
              this.back('result')
            }else if( res.data.message == '游戏继续') {
              if (res.data.data.out.player_id == this.player_id) {
                alert('您被淘汰了！')
                this.back('prepare')
              } else {
                alert(res.data.data.out.nickname + '被淘汰了！')
                this.back('prepare')
              }
            }
            clearInterval(this.loop)
          }else if(res.data.error == 502){
            clearInterval(this.loop)
            this.resultInfo = res.data.data
            this.playInfo = res.data.data.member
            alert('票数相同，重新投票')
            setTimeout(function (){
              this.isPoll = false
            },2000)
          }else if(res.data.error == 501){
            this.resultInfo = res.data.data
          }

        })
      },
      touchstart (e) {

        if(this.isPoll){
          alert('哼哼，他就是卧底了')
          return
        }
        if (this.temporaryData.tracking) {
          return
        }
        // 是否为touch
        if (e.type === 'touchstart') {
          window.event? window.event.cancelBubble = true : e.stopPropagation();
          if (e.touches.length > 1) {
            this.temporaryData.tracking = false
            return
          } else {
            // 记录起始位置
            this.basicdata.start.t = new Date().getTime()
            this.basicdata.start.x = e.targetTouches[0].clientX
            this.basicdata.start.y = e.targetTouches[0].clientY
            this.basicdata.end.x = e.targetTouches[0].clientX
            this.basicdata.end.y = e.targetTouches[0].clientY
            // offsetY在touch事件中没有，只能自己计算
            this.temporaryData.offsetY = e.targetTouches[0].pageY - this.$el.offsetParent.offsetTop
          }
          // pc操作
        } else {
          this.basicdata.start.t = new Date().getTime()
          this.basicdata.start.x = e.clientX
          this.basicdata.start.y = e.clientY
          this.basicdata.end.x = e.clientX
          this.basicdata.end.y = e.clientY
          alert(this.basicdata.start.x)
          this.temporaryData.offsetY = e.offsetY
        }
        this.temporaryData.tracking = true
        this.temporaryData.animation = false
        // alert(JSON.stringify(this.temporaryData))
      },
      touchmove(e){

        // 记录滑动位置
        if (this.temporaryData.tracking && !this.temporaryData.animation) {
          if (e.type === 'touchmove') {
            e.preventDefault()
            this.basicdata.end.x = e.targetTouches[0].clientX
            this.basicdata.end.y = e.targetTouches[0].clientY
          } else {
            e.preventDefault()
            this.basicdata.end.x = e.clientX
            this.basicdata.end.y = e.clientY
          }
          // 计算滑动值
          this.temporaryData.poswidth = this.basicdata.end.x - this.basicdata.start.x
          this.temporaryData.posheight = this.basicdata.end.y - this.basicdata.start.y
          let rotateDirection = this.rotateDirection()
          let angleRatio = this.angleRatio()
          this.temporaryData.rotate = rotateDirection * this.offsetWidthRatio * 15 * angleRatio
        }
      },
      touchend(e){
        console.log('移动结束')
        this.temporaryData.tracking = false
        this.temporaryData.animation = true
        // 滑动结束，触发判断
        // 判断划出面积是否大于0.4
        if (this.offsetRatio >= 0.1) {
          // 计算划出后最终位置
          let ratio = Math.abs(this.temporaryData.posheight / this.temporaryData.poswidth)
          this.temporaryData.poswidth = this.temporaryData.poswidth >= 0 ? this.temporaryData.poswidth + 200 : this.temporaryData.poswidth - 200
          this.temporaryData.posheight = this.temporaryData.posheight >= 0 ? Math.abs(this.temporaryData.poswidth * ratio) : -Math.abs(this.temporaryData.poswidth * ratio)
          this.temporaryData.opacity = 0
          this.temporaryData.swipe = true
          this.nextTick()
          // 不满足条件则滑入
        } else {
          this.temporaryData.poswidth = 0
          this.temporaryData.posheight = 0
          this.temporaryData.swipe = false
          this.temporaryData.rotate = 0
        }
      },
      nextTick () {
        // 记录最终滑动距离
        this.temporaryData.lastPosWidth = this.temporaryData.poswidth
        this.temporaryData.lastPosHeight = this.temporaryData.posheight
        this.temporaryData.lastRotate = this.temporaryData.rotate
        this.temporaryData.lastZindex = 20
        // 循环currentPage
        this.temporaryData.currentPage = this.temporaryData.currentPage === this.playInfo.length - 1 ? 0 : this.temporaryData.currentPage + 1
        // currentPage切换，整体dom进行变化，把第一层滑动置最低
        this.$nextTick(() => {
          this.temporaryData.poswidth = 0
          this.temporaryData.posheight = 0
          this.temporaryData.opacity = 1
          this.temporaryData.rotate = 0
        })
      },
      onTransitionEnd (index) {
        let lastPage = this.temporaryData.currentPage === 0 ? this.playInfo.length - 1 : this.temporaryData.currentPage - 1
        // dom发生变化正在执行的动画滑动序列已经变为上一层
        if (this.temporaryData.swipe && index === lastPage) {
          this.temporaryData.animation = true
          this.temporaryData.lastPosWidth = 0
          this.temporaryData.lastPosHeight = 0
          this.temporaryData.lastOpacity = 0
          this.temporaryData.lastRotate = 0
          this.temporaryData.swipe = false
          this.temporaryData.lastZindex = -1
        }
      },
      prev () {
        this.temporaryData.tracking = false
        this.temporaryData.animation = true
        // 计算划出后最终位置
        let width = this.$el.offsetWidth
        this.temporaryData.poswidth = -width
        this.temporaryData.posheight = 0
        this.temporaryData.opacity = 0
        this.temporaryData.rotate = '-3'
        this.temporaryData.swipe = true
        this.nextTick()
      },
      next () {
        this.temporaryData.tracking = false
        this.temporaryData.animation = true
        // 计算划出后最终位置
        let width = this.$el.offsetWidth
        this.temporaryData.poswidth = width
        this.temporaryData.posheight = 0
        this.temporaryData.opacity = 0
        this.temporaryData.rotate = '3'
        this.temporaryData.swipe = true
        this.nextTick()
      },
      rotateDirection () {
        if (this.temporaryData.poswidth <= 0) {
          return -1
        } else {
          return 1
        }
      },
      angleRatio () {
        let height = this.$el.offsetHeight
        let offsetY = this.temporaryData.offsetY
        let ratio = -1 * (2 * offsetY / height - 1)
        return ratio || 0
      },
      inStack (index, currentPage) {
        let stack = []
        let visible = this.temporaryData.visible
        let length = this.playInfo.length
        for (let i = 0; i < visible; i++) {
          if (currentPage + i < length) {
            stack.push(currentPage + i)
          } else {
            stack.push(currentPage + i - length)
          }
        }
        return stack.indexOf(index) >= 0
      },
      // 非首页样式切换
      transform (index) {
        let currentPage = this.temporaryData.currentPage
        let length = this.playInfo.length
        let lastPage = currentPage === 0 ? this.playInfo.length - 1 : currentPage - 1
        let style = {}
        let visible = this.temporaryData.visible
        if (index === this.temporaryData.currentPage) {
          return
        }
        if (this.inStack(index, currentPage)) {
          let perIndex = index - currentPage > 0 ? index - currentPage : index - currentPage + length
          style['opacity'] = '1'
          style['transform'] = 'translate3D(0,0,' + -1 * 60 * (perIndex - this.offsetRatio) + 'px' + ')'
          style['zIndex'] = visible - perIndex
          if (!this.temporaryData.tracking) {
            style[this.temporaryData.prefixes.transition + 'TimingFunction'] = 'ease'
            style[this.temporaryData.prefixes.transition + 'Duration'] = 300 + 'ms'
          }
        } else if (index === lastPage) {

          style['transform'] = 'translate3D(' + this.temporaryData.lastPosWidth + 'px' + ',' + this.temporaryData.lastPosHeight + 'px' + ',0px) ' + 'rotate(' + this.temporaryData.lastRotate + 'deg)'
          style['opacity'] = this.temporaryData.lastOpacity
          style['zIndex'] = this.temporaryData.lastZindex
          style[this.temporaryData.prefixes.transition + 'TimingFunction'] = 'ease'
          style[this.temporaryData.prefixes.transition + 'Duration'] = 300 + 'ms'
        } else {
          style['zIndex'] = '-1'
          style['transform'] = 'translate3D(0,0,' + -1 * visible * 60 + 'px' + ')'
        }
        return style
      },
      // 首页样式切换
      transformIndex (index) {
        if (index === this.temporaryData.currentPage) {
          let style = {}
          style['transform'] = 'translate3D(' + this.temporaryData.poswidth + 'px' + ',' + this.temporaryData.posheight + 'px' + ',0px) ' + 'rotate(' + this.temporaryData.rotate + 'deg)'
          style['opacity'] = this.temporaryData.opacity
          style['zIndex'] = 10
          if (this.temporaryData.animation) {
            style[this.temporaryData.prefixes.transition + 'TimingFunction'] = 'ease'
            style[this.temporaryData.prefixes.transition + 'Duration'] = (this.temporaryData.animation ? 300 : 0) + 'ms'
          }
          return style

        }
      }
    },
    created(){
      this.room_id = this.$route.params.room_id || window.localStorage.getItem('room_id');
      this.player_id = this.$route.params.player_id || window.localStorage.getItem('player_id')
      this.getUserInfo()
    },
    mounted(){
      if (window.history && window.history.pushState) {
        history.pushState(null, null, null,null,null);
        window.addEventListener('popstate', this.goBack, false);
      }

    },

  }
</script>

<style scoped>
  .el-container{
    width: 100%;
    position: absolute;
    top: 0;
  }
  .el-header {
    background:url('../assets/imgs/topBG.jpg') no-repeat;
    background-size:cover;
    background-position:bottom right;
    color: #fff;
    text-align: center;
    line-height: 60px;
  }
  .name{
    position: absolute;
    width: 100%;
    text-align: center;
    bottom: -40px;
    text-align: center;
    color: #fff;
  }
  .Tstext{
    text-align: center;
    color: olivedrab;
    padding: 10px 0;
  }
  .players{
    padding: 0 10px;
    margin: 10px 0;
    display: flex;
    flex-wrap:wrap
  }
  .hasplayer{
    width: 60px;
    height: 60px;
    position: relative;
    border-radius: 50%;
    overflow: hidden;
    border: 2px solid #67C23A;
    margin:10px calc((25% - 64px)/2);
  }
  .poll{
    width: 40%;
    background: darkslategrey;
    padding: 10px 20px;
    margin: 20px auto;
    border-radius: 4px;
    text-align: center;
    color: #fff;
  }
  img{
    position: absolute;
    width: 100%;
    height: 100%;
  }
  .imgBox{
    position: absolute;
    cursor: pointer;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
  }
  .result{
    width: 80%;
    background: #f2f2f2;
    margin: auto;
    margin-top: 4%;
    border-radius: 10px;
  }
  .pollHeader{
    text-align: center;
    line-height: 40px;
  }
  .pollContent{
    min-height: 120px;
    padding: 10px;
    background: #e3e3e3;
    display: flex;
    flex-wrap: wrap;
  }
  .options{
    height: 20px;
    line-height: 20px;
    width:44%;
    display: flex;
    justify-content: space-between;
    padding:0 3%;
  }
  .mark{
    transform: rotate(-30deg);
    background: #fff;
    color: brown;
    height: 20px;
    position: absolute;
    text-align: center;
    bottom: 20px;
    font-weight: 700;
    line-height: 20px;
    z-index: 22;
    width: 100%;
  }
  .transition-box {
    margin: auto;
    margin-bottom: 10px;
    width: 200px;
    border-radius: 4px;
    background-color: #409EFF;
    text-align: center;
    color: #fff;
    padding: 40px 20px;
    box-sizing: border-box;
  }
</style>
